package com.xyu.gulimall.product.exception;

import com.xyu.common.exception.BizCodeEnume;
import com.xyu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "com.xyu.gulimall.product.controller")
@Slf4j
public class GulimallExceptionControllerAdvice {

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidatedException(MethodArgumentNotValidException e){
        log.info("数据不符合规则"+e.getMessage()+e.getClass());
        Map<String,String> map = new HashMap<>();
        //返回异常信息
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(fieldError -> map.put(fieldError.getField(),fieldError.getDefaultMessage()));

        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.VALUE_EXCEPTION.getMsg()).put("data",map);
    }

}
